var currentTab;

// background.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

    if (message.action == "getcookies") {
        console.log('getcookies.');
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            if (tabs.length > 0 && tabs[0].id) {
                currentTab = tabs[0];
                executeScriptInActiveTab(currentTab);
                chrome.cookies.getAll({url: currentTab.url}, function (cookies) {
                    sendResponse({cookies: cookies});
                });
            }
        });
        return true;
    }

    if (message.action === "getDOM") {
        console.log('getDOM.');
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (tabs.length > 0 && tabs[0].id) {
                chrome.scripting.executeScript(
                    {
                        target: { tabId: tabs[0].id },
                        func: () => document.documentElement.outerHTML,
                    },
                    (results) => {
                        if (chrome.runtime.lastError) {
                            sendResponse({ outerHTML: '' });
                        } else {
                            sendResponse({ outerHTML: results[0].result });
                        }
                    }
                );
            } else {
                console.error('No active tab found.');
                sendResponse({ outerHTML: '' });
            }
        });
        return true;
    }


    if (message.action === "getHTML") {
        chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            chrome.scripting.executeScript({
                target: { tabId: tabs[0].id },
                function: () => document.documentElement.outerHTML
            }, function(results) {
                sendResponse({ outerHTML: results[0].result });
            });
        });
        return true; // 必须返回 true，以便异步消息通信正确工作
    }



});

function executeScriptInActiveTab(tab) {
    return new Promise((resolve, reject) => {
        if (tab.id) {
            chrome.scripting.executeScript({
                target: {tabId: tab.id},
                files: ['content.js']
            }, () => {
                console.log('Content script executed for tab ID:', tab.id);
                resolve(); // 成功执行时调用 resolve()
            });
        }
    });
}

function executeUserScript(script) {
    try {
        eval(script);
    } catch (error) {
        console.error('Error executing user script:', error);
    }
}

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.type === 'executeScript') {
        executeUserScript(message.script);
    }
});









